/*
 * event.c
 */

#include <stdio.h>
#include <stdlib.h>
#include <utils/error.h>
#include "action.h"
#include "event.h"

#define ETLIST_SIZE 20

/*
 * The list of action handlers. The corresponding event_t is simply the index
 * to this array.
 *
 * TODO: Add a mask for registered handlers to be able to correctly throw an
 * error when an invalid event_t is given.
 */
event * (*event_type_list[ETLIST_SIZE])(action*);

unsigned int event_type_list_size = 0;

/*
 * Calls the registered event handler of the event_t in the given action,
 * passing the given action to it.
 * Returns the event generated from the event handler.
 */
event * event_generate( action *a ) {
    return (event_type_list[a->type])(a);
}

/*
 * Registers the given event handler, returning the generated event_t.
 */
event_t event_register( event * (*event_handler)(action*) ) { 
    if( event_type_list_size < ETLIST_SIZE - 1 ) {
        event_type_list[event_type_list_size] = event_handler;
        event_type_list_size++;
        return (event_t)(event_type_list_size - 1);
    }
    else {
        printerr( ERROR_CONT_EVENTTCREATE );
        return (event_t)(-1);
    }
}

/*
 * Frees the given event, freeing the event_details struct with it.
 */
void free_event(event *e) {
    if( e != NULL ) {
        free(e->info); /* Goodbye event details */
        free(e); /* Goodbye event */
    }
    else {
        printerr( WARNING_CONT_EVENTFREE );
    }
}
